package logic

import (
	"context"
	"fmt"
	"teatch/model/cache"
	"teatch/model/mysql"

	"teatch/teacherrpc/internal/svc"
	"teatch/teacherrpc/teacherrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPasswordLogic) ForgetPassword(in *teacherrpc.ForgetPasswordRequest) (*teacherrpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.Student
	mysql.DB.Where("account=?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在")
	}

	sendSms, _ := cache.Rdb.Get(l.ctx, "SendKey"+in.Account).Result()
	if sendSms != in.SendSms {
		return nil, fmt.Errorf("短信验证码不正确")
	}

	if in.NewPassword != in.Password {
		return nil, fmt.Errorf("两次输入的新密码不一致,请重新输入")
	}

	user.Password = in.Password
	mysql.DB.Updates(&user)

	return &teacherrpc.ForgetPasswordResponse{
		StudentId: int64(user.ID),
	}, nil
}
